<template>
    <div class="chat">
        <el-container style="height:100%">
            <el-aside width="200px" class="side" style="height:100%;overflow:auto;">
                <el-button @click="test">test stream</el-button>
                {{ cmessage }}
            </el-aside>
            <el-main class="body">
                <chat ref="chatBox" v-model:messages="history" @message-send="sendMessageHandle"
                      align="leftright">
                    <!--                        suggest 插槽示例 -->
                    <!--                        <template v-slot:chatBoxSuggest="scope">-->
                    <!--                            <span v-for="sug in scope.suggest">{{sug}}</span>-->
                    <!--                        </template>-->
                    <!--                        process 插槽示例 -->
                    <!--                        <template v-slot:chatBoxProcess="scope">-->
                    <!--                            {{scope.process}}-->
                    <!--                        </template>-->
                    <!--                        <template v-slot:loading><span>loading</span></template>-->
                </chat>
            </el-main>
        </el-container>
    </div>
</template>
<script setup>
import {ref, reactive, onMounted, nextTick} from 'vue'
import chat from './chat/Index.vue'
import {doChat} from '@/api/chat.js'
import {fetchEventSource} from "@microsoft/fetch-event-source";

const props = defineProps({})
const emits = defineEmits([])
const userInput = ref('开始游戏');
const loading = ref(false)
const history = ref(
    [
        {
            role: 'system',
            id: '1',
            createAt: 1715676751919,
            content: "Hello, I'm your AI assistant.",
        },
        {
            role: 'user',
            id: '2',
            createAt: 1715676751919,
            content: "给一个 Semi Design 的 Button 组件的使用示例",
        },
        {
            role: 'assistant',
            id: '3',
            createAt: 1715676751919,
            content: "以下是一个 Semi 代码的使用示例：\n\`\`\`jsx \nimport React from 'react';\nimport { Button } from '@kousum/semi-ui-vue';\n\nconst MyComponent = () => {\n  return (\n    <Button>Click me</Button>\n );\n};\nexport default MyComponent;\n\`\`\`\n",
            suggest: ['你给我再提点建议', '你可以询问我天气信息'],
            process: [
                {
                    groupId: 1,
                    type: 'nodeStart',
                    groupName: 'span',
                },
                {
                    groupId: 1,
                    type: 'nodeInput',
                    data: {searchKey: '1', searchCity: '郑州市'},
                },
                {
                    groupId: 1,
                    type: 'logger',
                    data: '这个问题我可能没有办法回答你',
                },
                {
                    groupId: 1,
                    type: 'nodeOutput',
                    data: '你好呀。',
                },
                {
                    groupId: 2,
                    type: 'nodeStart',
                    groupName: '天气查询',
                },
                {
                    groupId: 2,
                    type: 'nodeInput',
                    data: {searchKey: '1', searchCity: '郑州市'},
                },
            ]
        },
        {
            role: 'assistant',
            id: '34',
            createAt: 1715676751919,
            content: "以下是一个 Semi 代码的使用示例：\n\`\`\`jsx \nimport React from 'react';\nimport { Button } from '@kousum/semi-ui-vue';\n\nconst MyComponent = () => {\n  return (\n    <Button>Click me</Button>\n );\n};\nexport default MyComponent;\n\`\`\`\n",
        },
        {
            role: 'assistant',
            id: '323',
            createAt: 1715676751919,
            status: 'error',
            content: "以下是一个 Semi 代码的使用示例：",
        },
        {
            role: 'assistant',
            id: '32312',
            createAt: 1715676751919,
            contentType: 'html',
            content: "<div style='width:300px;height:100px;color:red;'>Hello World.<br/>This is Html Document.<br/><button style='cursor:pointer;border:1px solid #3a72e1;border-radius: 5px;padding:4px 10px;'>Click Me</button></div>",
        }
    ]
)
const cmessage = ref('')
const chatBox = ref(null)
let abortController = null

const test = () => {
    let count = 0
    const source = new EventSource("http://127.0.0.1:8911/agent/endless")
    source.onmessage = function (event) {
        // 接收到服务器端发送的数据时触发
        count++
        if (count === 10) {
            source.close()
        }
        console.log(event)
    };
    source.onerror = function (event) {
        // 接收到服务器端发送的数据时触发
        console.log(event)
    };
    source.onopen = function (event) {
        // 接收到服务器端发送的数据时触发
        console.log(event)
    };

}


const sendMessageHandle = (message) => {
    console.log('sendMessageHandle', message)
    history.value.push({
        role: 'user',
        id: new Date().getTime(),
        createAt: 1715676751919,
        content: message,
    })
    history.value.push({
        role: 'assistant',
        id: new Date().getTime() + 22,
        createAt: 1715676751919,
        content: '',
        status: 'loading',
    })
    setTimeout(() => {
        let message = history.value.slice(-1)[0]
        message.content = 'Hello, I\'m your AI assistant.\n I like to play with you. \n and you ?Hello, I\'m your AI assistant.\n I like to play with you. \n and you ?Hello, I\'m your AI assistant.\n I like to play with you. \n and you ?'
        message.status = 'complete'

        nextTick(() => {
            chatBox.value.scrollToBottom()
        })
    }, 2000)
//     todo 发送消息到后端
}


onMounted(() => {
    // test()
})
/**
 * 提交
 */
const submit = () => {
    console.log(userInput.value);
    history.value.push({
        role: 'user',
        content: userInput.value
    })
    chatStreamAnswer({
        chat_id: 'abcd',
        content: userInput.value,
        userMessage: userInput.value,
    })
}

//流式回答  是一个模块完成输出一个模块，不是一个字一个字的输出
const chatStreamAnswer = (data) => {
    const baseURL = import.meta.env.VITE_BASE_API_URL
    const url = '/ai/agents/chairman'//'/agent/multi_agent_stream'

    abortController = new AbortController();
    let message = ''

    const init = {
        method: 'post',
        signal: abortController.signal,
        openWhenHidden: true, // 取消visibilityChange事件
        headers: {
            "Content-Type": `application/json`,
        },
        onopen(ev) {
            console.log(ev)
        },
        async onmessage(ev) {
            try {
                data = JSON.parse(ev.data)
                if (!data.isFinished) {
                    // message += data.content
                    message += data
                } else {
                    history.value.push({
                        role: 'assistant',
                        content: data
                        // content: data.content//message
                    })
                    message = ''
                }
                cmessage.value += data
                // cmessage.value += data.content
                await nextTick()
            } catch (e) {
                console.error(e)
            }
        },
        onclose(ev) {
            loading.value = false;
            abortController && abortController.abort();
        },
        onerror(err) {
            // console.log("onerror:", err);
            loading.value = false;
            abortController.abort();
            eventSource.close();
        },
    };

    data && (init.body = JSON.stringify(data));
    // headers && (init.headers = headers);
    const eventSource = fetchEventSource(`${baseURL}${url}`, init);
}

</script>
<style lang="scss" scoped>
.chat {
    position: relative;
    height: 100%;
    width: 100%;

    .header {
        border-bottom: 1px solid #eee;
    }

    .side {
        border-right: 1px solid #eee;
    }

    .body {
        position: relative;
        display: flex;
        flex-direction: column;
        padding: 20px 100px;

        .his-content {
            flex: 1;
            width: 100%;
            height: max-content;
        }

        .prompt {
            width: 100%;
            height: 180px;
        }
    }
}
</style>